//
//  BPTVRoomViewController.m
//  BPTV
//
//  Created by baipeng on 2018/11/15.
//  Copyright © 2018年 Apple Inc. All rights reserved.
//

#import "BPTVRoomViewController.h"
#import "BPAVPlayer.h"
#import "BPTVListTableView.h"
@interface BPTVRoomViewController ()
@property(nonatomic,strong)BPTVListTableView *tvListView;
@end

@implementation BPTVRoomViewController{
    BOOL isNavHidden;//是否隐藏navgationBar
}
#pragma mark - life cyle 1、控制器生命周期
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self orientationToPortrait:UIInterfaceOrientationLandscapeLeft];
    [self createSubViewUI];
    [kAppDelegate.window addSubview:self.tvListView];
    [self defaultInit];
    isNavHidden = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationPlay) name:@"play" object:nil];
    [self setupServer];
}
#pragma mark - 2、不同业务处理之间的方法以
-(void)defaultInit{
    [[BPAVPlayer shareInstance] playWithUrlString:self.urlPath view:self.view frame:CGRectMake(0, 0, kScreenHeight, kScreenWidth)];
    [[BPAVPlayer shareInstance] play];

}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    isNavHidden = !isNavHidden;
    [self.navigationController setNavigationBarHidden:isNavHidden animated:YES];
    if (isNavHidden) {
        self.tvListView.hidden = isNavHidden;
    }
}
#pragma mark - Network 3、网络请求

#pragma mark - Action Event 4、响应事件
//TODO:显示隐藏频道列表
-(void)changeChannelBtnAction:(UIButton *)btn{
    self.tvListView.hidden = !self.tvListView.hidden;
}
//TODO:换源事件
-(void)changeSourceBtnAction:(UIButton *)btn{
    if ([btn.titleLabel.text isEqualToString:@"WiFi源"]) {
        //切换到WiFi源
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"wifi.plist"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:path]) {
            NSDictionary *tvDic = [[NSDictionary alloc] initWithContentsOfFile:path];
            NSLog(@"文件存在，处理%@",[tvDic allKeys]);
            [self.tvListView setTVRoomListTvNameDic:tvDic];
            [btn setTitle:@"本地源" forState:UIControlStateNormal];

        }else{
            NSLog(@"不存在，提示");
        }
    }else{
        //切换到本地源
        NSString *make = [[NSBundle mainBundle] pathForResource:@"tv" ofType:@"plist"];
        NSDictionary *tvDic = [[NSDictionary alloc] initWithContentsOfURL:[NSURL fileURLWithPath:make]];
        [self.tvListView setTVRoomListTvNameDic:tvDic];
        [btn setTitle:@"WiFi源" forState:UIControlStateNormal];
    }

}


#pragma mark - Call back 5、回调事件
//TODO: 处理应用后台恢复之后点击不能播放的问题
-(void)notificationPlay{
    [[BPAVPlayer shareInstance] play];
}
//TODO:开启服务
-(void)setupServer{
    BPWiFiUploadManager *manager = [BPWiFiUploadManager shareInstance];
    BOOL success = [manager startHTTPServerAtPort:[BPIPHelper deviceIPPort]];
    if (success) {
        [manager setFileUploadStartCallback:^(NSString *fileName, NSString *savePath) {
            NSLog(@"File %@ Upload Start", fileName);
        }];
        [manager setFileUploadProgressCallback:^(NSString *fileName, NSString *savePath, CGFloat progress) {
            NSLog(@"File %@ on progress %f", fileName, progress);
        }];
        [manager setFileUploadFinishCallback:^(NSString *fileName, NSString *savePath) {
            NSLog(@"File Upload Finish %@ at %@", fileName, savePath);
            NSLog(@"后缀 is %@", [savePath pathExtension]);
            if ([[savePath pathExtension] isEqualToString:@"plist"]) {
                NSLog(@"直播源后缀正确plist");
                NSDictionary *temp = [[NSDictionary alloc] initWithContentsOfFile:savePath];
                if (temp == nil) {
                    //解析不出来就退出、提示内容错误
                    NSLog(@"直播源错误");
                    return;
                }
                //尝试解析、解析成功，文件移动到document
                NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"wifi.plist"];
                NSFileManager *fileManager = [NSFileManager defaultManager];
                if ([fileManager fileExistsAtPath:path]) {
                    [fileManager removeItemAtPath:path error:nil];

                }
                NSError *error;
                BOOL copySuccess = [fileManager moveItemAtPath:savePath toPath:path error:&error];

                if (!copySuccess) {
                    NSLog(@"copy error is %@", error);
                }

            }else if ([[savePath pathExtension] isEqualToString:@"json"]) {
                NSLog(@"直播源后缀正确json");
                NSDictionary *tvDic = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:savePath] options:NSJSONReadingAllowFragments error:nil];
                if (tvDic.allKeys.count == 0) {
                    NSLog(@"直播源错误");
                    return;
                }
                NSFileManager *fileManager = [NSFileManager defaultManager];
                NSError *error;
                NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"wifi.plist"];
                if ([fileManager fileExistsAtPath:path]){
                    NSLog(@"有文件");
                }else{
                    NSLog(@"没有文件");
                    [fileManager copyItemAtPath:path toPath:path error:&error];
                }
                //写入.plist文件
                BOOL success = [tvDic writeToFile:path atomically:YES];
                if (success && [fileManager fileExistsAtPath:savePath]) {
                    [fileManager removeItemAtPath:savePath error:nil];
                }
            }else{
                NSLog(@"直播源后缀错误");
                //提示文件格式不对，删除
            }
        }];
    }
}
#pragma mark - Delegate 6、代理、数据源

#pragma mark - interface 7、UI处理
-(void)createSubViewUI{
    self.navigationItem.rightBarButtonItems = @[[[UIBarButtonItem alloc] initWithCustomView:[self createButton:@"WiFi源" action:@selector(changeSourceBtnAction:)]],[[UIBarButtonItem alloc] initWithCustomView:[self createButton:@"换台" action:@selector(changeChannelBtnAction:)]]];

    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth/2, kNavBarHeight)];
    label.text = [NSString stringWithFormat:@"http://%@:%hu",[BPWiFiUploadManager shareInstance].ip,[BPIPHelper deviceIPPort]];
    label.font = KFont(15);
    label.textColor = UIColor.whiteColor;
    label.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = label;
}
-(UIButton *)createButton:(NSString *)title action:(SEL)action{
    UIButton *button = [[UIButton alloc] init];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    button.bounds = CGRectMake(0, 0, 70, 30);
    button.contentEdgeInsets = UIEdgeInsetsMake(0,  0, 0, 0);
    [button sizeToFit];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    return button;
}
#pragma mark - lazy loading 8、懒加载
-(BPTVListTableView *)tvListView{
    if (!_tvListView) {
        _tvListView  = [[BPTVListTableView alloc]initWithFrame:CGRectMake(kScreenHeight-kScreenHeight/4, 0, kScreenHeight/4, kScreenWidth) style:UITableViewStyleGrouped];
        _tvListView.hidden = YES;
        kWeakSelf(self);
        _tvListView.BPTVListTableComBlack = ^(NSString *urlPath) {
            [[BPAVPlayer shareInstance] stop];
            weakself.urlPath = urlPath;
            [weakself defaultInit];
        };
    }
    return _tvListView;
}

#pragma mark - 强制旋转屏幕
- (void)orientationToPortrait:(UIInterfaceOrientation)orientation {
    SEL selector = NSSelectorFromString(@"setOrientation:");
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
    [invocation setSelector:selector];
    [invocation setTarget:[UIDevice currentDevice]];
    int val = orientation;
    [invocation setArgument:&val atIndex:2];
    [invocation invoke];
}
//是否允许自动旋转
- (BOOL)shouldAutorotate {
    return YES;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait;
}
//返回当前viewController支持的方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
}


-(void)dealloc{
    [[BPAVPlayer shareInstance] stop];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
